<?php
namespace app\api\controller\user;

use app\api\controller\BasicUserApi;
use think\Db;
use think\Exception;

class Address extends BasicUserApi
{
    public $table = 'StoreMemberAddress';

    /**
     * @Notes: 我的收货地址列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: Forska
     * @email: 736523388@qq.com
     * @DateTime: 2018/11/13 10:13
     */
    public function index(){
        $list = Db::name($this->table)
            ->where(['is_deleted'=>'0','status'=>'1','mid'=>UID])
            ->order('create_at desc')
            ->field('id,username,phone,province,city,area,address,is_default')
            ->select();
        return json(['msg'=>'success','data'=>$list]);
    }

    /**
     * 获取收货地址详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function view(){
        $id=$this->request->get('id/d');
        $address=Db::name($this->table)
            ->where('id',$id)
            ->field('username,phone,province,city,area,address,is_default,id')
            ->find();
        return json(['msg'=>'success','data'=>$address]);
    }

    /**
     * 添加/编辑收货地址
     * @return \think\response\Json
     * @throws Exception
     */
    public function ui(){
        $data = [
            'username' => $this->request->param('username'),
            'phone' => $this->request->param('phone'),
            'province' => $this->request->param('province'),
            'city' => $this->request->param('city'),
            'area' => $this->request->param('area'),
            'address' => $this->request->param('address'),
            'id' => $this->request->param('id',0),
            'is_default' => $this->request->param('is_default',0),
            'mid' => UID
        ];
        $validate = Validate('Address');
        $res = $validate->check($data);
        if(false === $res) {
            return json(['msg'=>$validate->getError()],403);
        }
        $address_num=Db::name($this->table)->where('mid',UID)->count();
        Db::startTrans();
        try{
            if($address_num<1) {
                //将这个地址设为默认地址
                $data['is_default'] = 1;
            }elseif ($data['is_default']){
                //将默认地址取消
                Db::name($this->table)
                    ->where('mid',UID)
                    ->where('is_default',1)
                    ->setField('is_default',0);
            }
            if($data['id']){
                //修改
                unset($data['is_default']);
                Db::name($this->table)
                    ->update($data);
            }else{
                //新增
                Db::name($this->table)
                    ->insert($data);
            }
        }catch (Exception $e){
            Db::rollback();
            throw new Exception($e);
        }
        Db::commit();
        return json(['msg'=>'数据保存成功']);
    }

    /**
     * 删除收货地址
     * @throws Exception
     */
    public function delete(){
        $map = [
            'id' => $this->request->param('id'),
            'mid' => UID
        ];
        $is_default=Db::name($this->table)->where($map)->value('is_default');
        Db::startTrans();
        try{
            Db::name($this->table)->where($map)->delete();
            if($is_default){
                $temp=Db::name($this->table)
                    ->where('mid',UID)
                    ->field('id')->find();
                if($temp){
                    Db::name($this->table)
                        ->where('mid',UID)
                        ->where('id',$temp['id'])
                        ->setField('is_default',1);
                }
            }
        }catch (\Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
        Db::commit();
        return json(['msg'=>'删除成功']);
    }

    /**
     * 设为默认地址
     * @return \think\response\Json
     * @throws Exception
     */
    public function todefault(){
        $map = [
            'id' => $this->request->param('id'),
            'mid' => UID
        ];
        Db::startTrans();
        try{
            Db::name($this->table)
                ->where('mid',UID)
                ->where('is_default',1)
                ->setField('is_default',0);
            Db::name($this->table)
                ->where($map)
                ->setField('is_default',1);
        }catch (\Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
        Db::commit();
        return json(['msg'=>'设置成功']);
    }
}